﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using MShop.Core.Domain;
using MShop.Core.DataAccess;
 

namespace MShop.Web.Areas.Admin.Controllers
{
    public class ItemCatController : SecureController
    {
        private readonly IItemCatDao _ItemCatDao;
        public ItemCatController(IItemCatDao itemcatdao)
        {
            _ItemCatDao = itemcatdao;
        }
        
        public ActionResult Index()
        {
            ViewData["itemcats"] = _ItemCatDao.Build();
            return View();
        }
        public ActionResult Create()
        {
            ViewData["selectlist"] = _ItemCatDao.BuildSelectList(null,true);
            ViewData["itemcats"] = _ItemCatDao.Build();            
            return View(new ItemCat());
        }

        [HttpPost]
        public ActionResult Create(ItemCat itemcat)
        {
           
            ViewData["itemcats"] = _ItemCatDao.Build();
            if (ModelState.IsValid)
            {
                _ItemCatDao.Save(itemcat);
                _ItemCatDao.SaveChanges();
                return RedirectToAction("index");
            }
            ViewData["selectlist"] = _ItemCatDao.BuildSelectList(itemcat.Id, true);
            return View(itemcat);
        }

        public ActionResult Edit(int id)
        {
            ViewData["selectlist"] = _ItemCatDao.BuildSelectList(null, true);
            ViewData["itemcats"] = _ItemCatDao.Build();

            return View(_ItemCatDao.GetById(id));
        }

        [HttpPost]
        public ActionResult Edit(int id,ItemCat itemcat)
        {
            ViewData["selectlist"] = _ItemCatDao.BuildSelectList(null,true);
            ViewData["itemcats"] = _ItemCatDao.Build();
            if (ModelState.IsValid)
            {
                var cat = _ItemCatDao.GetById(id);
                cat.Name = itemcat.Name;
                cat.ParentId = itemcat.ParentId;
                _ItemCatDao.SaveChanges();
                return RedirectToAction("index");
            }
            return View(itemcat);

            
        }






        public ActionResult Delete(int id)
        {
            _ItemCatDao.Delete(_ItemCatDao.GetById(id));
            _ItemCatDao.SaveChanges();
            return RedirectToAction("index");
        }
    }
}
